#!/bin/gawk -f
# qguessr: Script to guess restraint file type (i.e. program type).
# Input variables: 
#   mr:      if 0, don't look for coordinate section of an mr file
#            else, stop at start of coordinate section
#   filtyp:  if 0, determine filtyp; else don't
#   fatal:   if not 0, stop at error; otherwise continue
# Exit code: the file type number, or 0 on error (!)
#            100 is added to value if start of coordinate section of mr-file 
#                was found
# =============================================================
# Ton Rullmann, December 4, 1995
# =============================================================
# File type 1 = DISGEO
#           2 = XPLOR
#           3 = BIOSYM
#           4 = DISMAN/DIANA
#          99 = user defined

BEGIN {
    if ( ARGC <= 1 ) {
	print "usage: qguessr [mr=1] [filtyp=1/2/3/4/99] [fatal=1] file"
	exit ( 1 )
    }
    filtyp_fnd = 0
    filtyp_unk = 99
    mr_fnd = 0
    checkd = 0
}

function error() {
    filtyp_fnd = 0
    exit
}

function checkft( num ) {
    if ( filtyp || filtyp_fnd == filtyp_unk ) return
    if ( !filtyp_fnd )
	filtyp_fnd = num
    else {
	if ( filtyp_fnd != num ) {
	    print "* Inconsistent file type. Previously found type", filtyp_fnd, "now", num
	    print "* At line:", org 
	    if ( fatal ) 
		error()
	    else
		filtyp_fnd = filtyp_unk
	}
    }
    checkd = 1
}

# start processing - first change to uppercase

    {
    org = $0
    $0 = toupper( $0 )
}

# DISGEO type

/^NOEUPP / || /^HBUPP  / || /^SSUPP  / || \
/^NOELOW / || /^HBLOW  / || /^SSLOW  / || \
/^ANGLE  / || /^JCOUPL / || /^SHIFTS / { 
    checkft( 1 )
    next
}

# XPLOR type

/^ *ASSI/ {
    checkft( 2 )
    next
}

# BIOSYM type

/^!BIOSYM *RESTRAINT/ {
    checkft( 3 )
    next
}

# DISMAN/DIANA type

/DISMAN/ {
    checkft( 4 )
    next
}

/DIANA/ {
    checkft( 4 )
    next
}

NF == 2 && $1 ~ /^[0-9]+$/ {
    checkft( 4 )
    next
}

# Start of coordinate section of "mr" file

mr  {
    if ( $0 ~ /^ *START OF MODEL/ || $0 ~ /^ *ENTRY H ATOM NAME/ || \
         $0 ~ /^ *RAW FILE HAD/ )  {
	mr_fnd = 1
	exit
    }
}

END {
    if ( !filtyp ){
	if ( filtyp_fnd == 0 ) {
	    if ( checkd )
		print "* Restraint file type could not be determined due to error(s)"
	    else
		filtyp_fnd = filtyp_unk
	}
	if ( filtyp_fnd == filtyp_unk ) print "* Restraint file type UNKNOWN"
	if ( filtyp_fnd == 1 ) print "* Restraint file type determined as DISGEO"
	if ( filtyp_fnd == 2 ) print "* Restraint file type determined as XPLOR"
	if ( filtyp_fnd == 3 ) print "* Restraint file type determined as BIOSYM"
	if ( filtyp_fnd == 4 ) print "* Restraint file type determined as DIANA/DISMAN"
    }
    if ( mr_fnd ) {
	print "* Restraint file is MR file"
	filtyp_fnd += 100
    }
    exit( filtyp_fnd )
}
